package com.dhcc.core.modules.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.core.framework.annotion.CacheClear;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.constant.Const;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.util.ArrayUtil;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.system.cache.dict.IDictCache;
import com.dhcc.core.modules.system.dao.DictMapper;
import com.dhcc.core.modules.system.entity.Dict;
import com.dhcc.core.modules.system.service.IDictService;

/**
 * 字典服务
 *
 * @ClassName: DictServiceImpl
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午10:39:46
 */
@Service
@Transactional
public class DictServiceImpl extends BaseServiceImpl<DictMapper, Dict> implements IDictService {

    @Autowired
    DictMapper dictMapper;

    /**
     * 每个条目之间的分隔符
     */
    public static final String ITEM_SPLIT = ";";

    /**
     * 属性之间的分隔符
     */
    public static final String ATTR_SPLIT = ":";

    /**
     * 拼接字符串的id
     */
    public static final String MUTI_STR_ID = "ID";

    /**
     * 拼接字符串的key
     */
    public static final String MUTI_STR_KEY = "KEY";

    /**
     * 拼接字符串的value
     */
    public static final String MUTI_STR_VALUE = "VALUE";
    /**
     * 拼接字符串的value
     */
    public static final String MUTI_STR_WEIGHT = "WEIGHT";

    @Override
    @Transactional
    @CacheClear(IDictCache.CACHE_NAME)
    public void addDict(Dict dict, String dictValues) {
        // 判断有没有该字典
        List<Dict> dicts = dictMapper
                .selectList(new EntityWrapper<Dict>().eq("name", dict.getName()).and().eq("PARENT_ID", 0));
        if (dicts != null && dicts.size() > 0) {
            throw new BizException(BizExceptionEnum.DICT_EXISTED);
        }

        // 解析dictValues
        List<Map<String, String>> items = parseKeyValue(dictValues);

        // 添加字典
        Dict newDict = new Dict();
        newDict.setName(dict.getName());
        newDict.setWeight(dict.getWeight());
        newDict.setCode(dict.getCode());
        newDict.setDescription(dict.getDescription());
        newDict.setParentId(Const.TREE_ROOT_ID);
        newDict.setCategoryId(dict.getCategoryId());
        newDict.setDeptId(dict.getDeptId());
        this.dictMapper.insert(newDict);

        // 添加字典条目
        for (Map<String, String> item : items) {
            String key = item.get(MUTI_STR_KEY);
            String name = item.get(MUTI_STR_VALUE);
            String weight = item.get(MUTI_STR_WEIGHT);
            Dict itemDict = new Dict();
            itemDict.setParentId(newDict.getId());
            itemDict.setName(name);
            itemDict.setKey(key);
            itemDict.setWeight(Integer.valueOf(weight));
            this.dictMapper.insert(itemDict);
        }
    }

    @Override
    @Transactional
    @CacheClear(IDictCache.CACHE_NAME)
    public void editDict(Dict dict, String dicts) {
        // 删除之前的字典
        this.delteDict(dict.getId());

        // 重新添加新的字典
        this.addDict(dict, dicts);
    }

    @Override
    @Transactional
    @CacheClear(IDictCache.CACHE_NAME)
    public void delteDict(Long dictId) {
        // 删除这个字典的子词典
        Wrapper<Dict> dictEntityWrapper = new EntityWrapper<>();
        dictEntityWrapper = dictEntityWrapper.eq("PARENT_ID", dictId);
        dictMapper.delete(dictEntityWrapper);

        // 删除这个词典
        dictMapper.deleteById(dictId);
    }

    /**
     * 解析一个组合字符串(例如: "1:启用;2:禁用;3:冻结" 这样的字符串)
     *
     * @author cyf
     * @Date 2017/4/27 16:44
     */
    private List<Map<String, String>> parseKeyValue(String mutiString) {
        if (CommonUtil.isEmpty(mutiString)) {
            return new ArrayList<>();
        } else {
            ArrayList<Map<String, String>> results = new ArrayList<>();
            String[] items = ArrayUtil.stringToArray(CommonUtil.removeSuffix(mutiString, ITEM_SPLIT), ITEM_SPLIT);
            for (String item : items) {
                String[] attrs = item.split(ATTR_SPLIT);
                HashMap<String, String> itemMap = new HashMap<>();
                itemMap.put(MUTI_STR_KEY, attrs[0]);
                itemMap.put(MUTI_STR_VALUE, attrs[1]);
                itemMap.put(MUTI_STR_WEIGHT, attrs[2]);
                results.add(itemMap);
            }
            return results;
        }
    }

    @Override
    public List<Map<String, Object>> list(Long categoryId,String conditiion) {
        return this.baseMapper.list(categoryId,conditiion);
    }
    @Override
    public List<Map<String, Object>> list(Long categoryId,String conditiion,Long deptId) {
        return this.baseMapper.list(categoryId,conditiion,deptId);
    }

    /**
     * 查询字典列表
     *
     * @author liqingyang
     * @Date 2019/1/16 13:04
     */
    public List<Map<String, Object>> pageList(Page<Dict> page,Long categoryId, String conditiion){
        return this.baseMapper.list(page,categoryId,conditiion);
    }
}
